/*
 * Copyright (c) 2019. Mikes. All rights reserved.
 *
 * You can contact me with sending email to bWlrZXNfMjAxMkAxNjMuY29t for more information!
 */

package com.climber.android.auth.ui

import android.text.TextUtils
import android.text.method.LinkMovementMethod
import com.alibaba.android.arouter.launcher.ARouter
import com.climber.android.auth.R
import com.climber.android.auth.api.AuthService
import com.climber.android.auth.api.LoginRequestInfo
import com.climber.android.auth.entity.SocialRegisterCompleteEvent
import com.climber.android.commonres.app.AppAccount
import com.climber.android.commonres.app.service.TokenResponseTransfer
import com.climber.android.commonres.entity.IncUserInfo
import com.climber.android.commonres.helper.onClick
import com.climber.android.commonres.ui.BaseMVPActivity
import com.climber.android.commonres.util.UIHelper
import com.climber.android.commonsdk.api.APIError
import com.climber.android.commonsdk.api.ApiObserver
import com.climber.android.commonsdk.api.GlobalErrorProcessor
import com.climber.android.commonsdk.app.AppEnv
import com.climber.android.commonsdk.arouter.ARouterPathConstants
import com.climber.android.commonsdk.event.BusProvider
import com.climber.android.commonsdk.event.CommonBusEvent
import com.climber.android.commonsdk.util.APIDataHelper
import com.climber.android.commonsdk.util.WebLinkClickSpan
import io.ganguo.library.mvp.http.RxSchedulers
import io.ganguo.library.mvp.ui.mvp.IPresenter
import io.ganguo.library.mvp.ui.mvp.di.component.AppComponent
import io.ganguo.library.mvp.util.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.auth_activity_social_signup.*

/**
 * Created by Mikes at 2019-11-04 15:14
 * follow steps
 *
 * 1.用户点击社交登录
 * 2.该社交账号未注册过，需要绑定手机号 (登录页)
 * 3.输入手机号获取验证码，校验！()
 * 4.已在系统内注册，但是未绑定，则自动绑定该手机号，返回20000
 * 5.已在系统内注册，但已绑定其他账号，提示用户"此手机号已绑定其他账号" 返回20002
 * 6.未在系统内注册，则进入下一个页面要求用户输入昵称，密码，完成社交账号注册。同时需要自动绑定该手机号。
 */
class AuthSocialSignUpActivity : BaseMVPActivity<IPresenter>() {
    private val phoneNumber: String by lazy {
        intent.getStringExtra("phoneNumber")
    }

    private val socialRequest: LoginRequestInfo by lazy {
        intent.getSerializableExtra("socialRequest") as LoginRequestInfo
    }

    override fun setupActivityComponent(appComponent: AppComponent) {
    }

    override fun getLayoutResourceId(): Int = R.layout.auth_activity_social_signup

    override fun initView() {
        tv_register_privacy.movementMethod = LinkMovementMethod.getInstance()
        tv_register_privacy.text = SpanUtils()
                .append("我已阅读并同意")
                .setForegroundColor(UIUtils.getColor(R.color.common_text_secondary_light))
                .append("《服务协议》")
                .setForegroundColor(UIUtils.getColor(R.color.common_green))
                .setClickSpan(WebLinkClickSpan(AppEnv.USER_AGREEMENT_URL, preferTitle = "服务协议"))
                .append("和")
                .setForegroundColor(UIUtils.getColor(R.color.common_text_primary))
                .append("《隐私政策》")
                .setForegroundColor(UIUtils.getColor(R.color.common_green))
                .setClickSpan(WebLinkClickSpan(AppEnv.PRIVACY_AGREEMENT_URL, preferTitle = "隐私政策"))
                .create()
    }

    override fun initListener() {
        cbRegisterPrivacy.setOnCheckedChangeListener { _, isChecked ->
            tv_register_now.isEnabled = isChecked
        }

        sv_register.setOnTouchListener { _, _ ->
            KeyboardUtils.hideSoftInput(this)
            false
        }

        tv_register_now.onClick {
            doSocialRegister()
        }
    }

    override fun initData() {
    }

    private fun doSocialRegister() {
        val nickName = nicknameView.getInputContent()
        val password = passwordView.getInputContent()
        val passwordAgain = passwordAgainView.getInputContent()

        if (TextUtils.isEmpty(nickName)) {
            ToastHelper.toastMessage(R.string.nickname_empty)
            return
        }

        if (TextUtils.isEmpty(password) || TextUtils.isEmpty(passwordAgain)) {
            ToastHelper.toastMessage(R.string.input_password)
            return
        }

        if (!StringUtils.equals(password, passwordAgain)) {
            ToastHelper.toastMessage(R.string.password_should_match)
            return
        }

        val requestInfo = mutableMapOf<String, String>()
        requestInfo.putAll(socialRequest.apiParameters())
        requestInfo["mobile"] = phoneNumber

        requestInfo["nick_name"] = nickName
        requestInfo["password"] = password
        requestInfo["re_password"] = password

        AuthService.authServiceAPI.socialRegister(APIDataHelper.generateRequestBody(requestInfo))
                .flatMap { registerApiResponse ->
                    if (registerApiResponse.isSuccessful()) {
                        val loginRequestInfo = LoginRequestInfo.Mobile(phoneNumber, password)
                        AuthService.authServiceAPI
                                .issueGetLoginToken(APIDataHelper.generateRequestBody(loginRequestInfo.apiParameters()))
                                .flatMap { rawResponse ->
                                    TokenResponseTransfer().apply(rawResponse)
                                }
                                .flatMap { tokenResponse ->
                                    if (tokenResponse.isSuccessful()) {
                                        AuthService.getUserCardInfoAndWalletInfo()
                                                .map { incUserInfo ->
                                                    incUserInfo.user_id = tokenResponse.data?.user_id

                                                    incUserInfo
                                                }
                                    } else {
                                        Observable.error(APIError.ServerError(errorCode = tokenResponse.getServerErrorCode(), errorMsg = tokenResponse.getServerErrorMsg()))
                                    }
                                }
                    } else {
                        Observable.error(APIError.ServerError(errorCode = registerApiResponse.getServerErrorCode(), errorMsg = registerApiResponse.getServerErrorMsg()))
                    }
                }
                .compose(RxSchedulers.networkRequest())
                .compose(GlobalErrorProcessor.processGlobalError(noticeErrorInfo = true))
                .doOnSubscribe { UIHelper.showLoading(this, null) }
                .subscribeOn(AndroidSchedulers.mainThread())
                .`as`(RxLifecycleUtils.bindLifecycle(this))
                .subscribe(object : ApiObserver<IncUserInfo>() {
                    override fun success(apiResponse: IncUserInfo) {
                        UIHelper.hideLoading()

                        AppAccount.incUserInfo = apiResponse
                        BusProvider.getInstance().post(CommonBusEvent.TokenChangeEvent(authorizated = true))
                        // 社交注册成功后，通知登录页面做一次ARouter跳转
                        BusProvider.getInstance().post(SocialRegisterCompleteEvent())
                        this@AuthSocialSignUpActivity.finish()
                    }

                    override fun dealError(apiError: APIError) {
                        super.dealError(apiError)
                        UIHelper.hideLoading()
                    }
                })
    }
}